package gateway.mgt.scaffold

import gateway.mgt.runtime.GatewayCore
import gateway.mgt.Heartbeat
import gateway.mgt.runtime.RuntimeMetrics

class GatewayCoreController {
    static scaffold = GatewayCore

    def refresh(Heartbeat heartbeat) {
        def core = GatewayCore.findByName(heartbeat.coreName)

        if (!core)
            core = new GatewayCore(name: heartbeat.coreName)

        if (!heartbeat.registered) {
            core.addToServices(heartbeat.serviceId)
            core.addToRegistrations("Service [$heartbeat.serviceId] registered at [${new Date().format("yyyy-MM-dd HH:mm:ss")}]")
        }

        def runtime = RuntimeMetrics.findByServiceId(heartbeat.serviceId)

        if (runtime)
            runtime.properties = [dateSent: heartbeat.dateSent, dateReceived: heartbeat.dateReceived]
        else
            core.addToRuntimes(serviceId: heartbeat.serviceId, dateSent: heartbeat.dateSent, dateReceived: heartbeat.dateReceived)

        if (core.save(flush: true))
            render "success"
        else
            render "failure"
    }
}
